"""
CSPBuilder plugin

Provides workspace folders

Copyright (c) 2008 Rune M. Friborg, runef@diku.dk.
See LICENSE.txt for licensing details (GPLv2).
"""

PLUGIN_NAME = "Workspaces"

try:
    import cPickle as pickle
except:
    import pickle

import os
import wx

from plugins.execute import *


class PluginWorkspaces(PluginEXECUTION):

    def __init__(self, pluginManager):
        PluginEXECUTION.__init__(self, pluginManager, PLUGIN_NAME)

        self.home = os.getenv('USERPROFILE') or os.getenv('HOME')
        self.confPathAndFilename = self.home + '/.cspbuilder/builder.conf'
        self.localConfPathAndFilename = '.cspbuilder/builder.conf'
        

        self.folders = []
        self._load_pref()


    def __load_all_pref(self):

        D = {}

        # Load
        if os.path.exists(self.localConfPathAndFilename) or os.path.exists(self.confPathAndFilename):
            if os.path.exists(self.localConfPathAndFilename):
                f = open(self.localConfPathAndFilename, 'r')
            else:
                f = open(self.confPathAndFilename, 'r')
                
            filedata = ''
            for line in f.readlines():
                filedata += line
            D = pickle.loads(filedata)
            f.close()            
        else:
            self._create_empty_pref()

        return D


    def _save_pref(self):
        
        D = self.__load_all_pref()

        D['workspace'] = self.folders

        f = open(self.confPathAndFilename, "wb")
        f.write(pickle.dumps(D))
        f.close()

        
    def _load_pref(self):

        D = self.__load_all_pref()

        if (D.has_key('workspace')):
            self.folders = D['workspace']
        else:
            self.folder = []

                        
    def _create_empty_pref(self):
        
        if not os.path.exists(self.home + '/.cspbuilder'):
            os.mkdir(self.home + '/.cspbuilder')

        D = {}
        f = open(self.confPathAndFilename, "wb")
        f.write(pickle.dumps(D))
        f.close()


    def _getFolderList(self, L):
        # Todo: Create support for several folders.
        L = L + self.folders
        return L

    def add_workspace(self, path):
        self.folders.append(path)
        self._save_pref()
        

    def print_workspaces(self):
        for folder in self._getFolderList([]):
            print folder
    
    def _updatePath(self, L):
        # Put workspace folders between index 0 and tail.
        return [L[0]] + self.folders + L[1:]
            

def load(pluginManager):

    p = PluginWorkspaces(pluginManager)
    p.addCommandLineArg('-aw', '--add-workspace', p.add_workspace, '\n  -aw, --add-workspace <path>	Add workspace folder\n', has_value=True)
    p.addCommandLineArg('-pw', '--print-workspaces', p.print_workspaces, '  -pw, --print-workspaces  	Print workspace folders\n')
    p.addList(pathlist_COMPONENTS, p._getFolderList)
    p.addUpdatePath(p._updatePath)
    pluginManager.addPlugin(p)


